import {useMemo, useRef, useState} from 'react';

export  default () => {
  const [pos, setPos] = useState({
    left: 0,
    top: 0
  })

  const curPos = useRef(pos);

  // 拖拽开始时候元素的位置及鼠标位置
  const dragData = useRef({
    startTop: 0,
    startLeft: 0,
    startX: 0,
    startY: 0
  })

  const moveDraggier = useMemo(() => {
    const mouseDown = (e: React.MouseEvent<HTMLDivElement>) => {
      document.addEventListener('mousemove', mouseMove);
      document.addEventListener('mouseup', mouseUp);

      dragData.current = {
        startTop: curPos.current.top,
        startLeft:  curPos.current.left,
        startX: e.clientX,
        startY: e.clientY
      }
    }

    const mouseMove = (e: MouseEvent) => {
      console.log(curPos.current);
      const {startTop, startLeft, startX, startY} = dragData.current;
      const durX = e.clientX - startX;
      const durY = e.clientY - startY;

      curPos.current = {
        top: durY + startTop,
        left: durX+ startLeft
      }

      setPos({
        top: durY + startTop,
        left: durX+ startLeft
      })
    }

    const mouseUp = () => {
      document.removeEventListener('mousemove', mouseMove);
      document.removeEventListener('mouseup', mouseUp);
    }
    return mouseDown;
  }, [])



  return <div>
    <div style={{
      'height': '50px',
      'width': '50px',
      'top': `${pos.top}px`,
      'left': `${pos.left}px`,
      'position': 'absolute',
      'background': '#000'
    }}
         onMouseDown={moveDraggier}
    />
  </div>
}
